<?php

namespace app\admin\service\goods;

use app\traits\Result;
use app\common\model\Goods as GoodsModel;
use app\common\model\GoodsAttr;
use app\common\model\GoodsAttrValue;
use app\common\model\GoodsAttrValueType;
use DOMDocument;
use DOMXPath;
use think\Exception;
use think\Service;


class GoodsService
{
    use Result;

    /**
     * 添加/编辑
     * @param $data
     * @param string $scene
     * @return array|string
     */
    public static function storeGoodsCate($data,$scene='add'){
      //  $data['state'] = isset( $data['state'])? $data['state']:0;
//        $data['start_time'] = strtotime($data['start_time']);
//        $data['end_time'] = strtotime($data['end_time']);

        $data['update_time'] = time();
        $model = new GoodsModel(); //实例化
        if(!empty($data) && !empty($data['name'])) {
            if ($scene == 'add') {
//                $data['create_time'] = time();


                $result = $model->save($data);
                if ($result) {
                    return Result::success('添加成功');
                } else {
                    return Result::error('添加失败');
                }
            } else {
                //$result = $model->where(['id'=>$data['id']])->find();
                unset($data['token']);
                $result = $model->exists(true)->update($data);
                //   $result->save($data);
                if ($result) {
                    return Result::success('编辑成功');
                } else {
                    return Result::error('编辑失败');
                }
            }
        }
        return false;
    }
    /**
     * 商品属性处理
     * 保存
     * params = []
    */
    public static function saveGoodsAttr($params=[]){
        if(!empty($params) && !empty($params['value'])){
            GoodsAttr::where(['goods_id'=>$params['goods_id']])->delete();
            foreach ($params['value'] as $key=>$vs){
                $model = new GoodsAttr(); //实例化
                $model->save([
                    'goods_id'=>$params['goods_id'],
                    'arrt_id'=>$vs['attr_arr'],
                    'sell_price'=>$vs['skuPrice'],
                    'original_price'=>$vs['SellPrice'],
                    'stock'=>$vs['skuStock'],
                    'create_time'=>time(),
                ]);
            }
            $goods = new GoodsModel(); //实例化
            $goods->where(['id'=>$params['goods_id']])->save(['attr_id'=>$params['type']]);
            return true;
        }
    }

    /**
     * 获取属性值 带价格
     * 含中文值
     * array
     **/

    public static function getGoodsAttrname($goods_id)
    {
        try {
            //属性值类型名称
            $goods = GoodsModel::where(['id'=>$goods_id])->find();
            $type_name = self::getAttrName($goods->attr_id);
            //print_r($type_name);exit;
            //或是属性的中文值
            $attr_arr = GoodsAttr::where(['goods_id' => $goods_id])->select()->toArray();
            //  print_r($attr_arr);exit;
            foreach ($attr_arr as $key => $vs) {
                //属性名称
                $value = GoodsAttrValue::whereIn('id', $vs['arrt_id'])->field('name')->order('type_id','DESC')->select()->toArray();
                $name = array_column($value, 'name');
              //  $name = implode(' + ', $name);
                $attr_arr[$key]['title'] = $name;

                //属性id
//                $attr_arr[$key]['specs'] = str_replace(',', '_', $vs['arrt_id'], $count);
                $attr_arr[$key]['spec'] =  explode(',',$vs['arrt_id']);

                //属性类型

            }

            return ['attr_arr'=>$attr_arr,'type_name'=>$type_name,'attr_id'=>self::getAttrId($goods_id)];
        } catch (Exception $exception) {
            return $exception->getMessage();
        }
    }

    /**
     * 获取商品属性值类型名称
    */
    public static function getAttrName($type_id){

        $name = GoodsAttrValueType::where(['state'=>1,'type_id'=>$type_id])->field('name')->order('id','DESC')->select()->toArray();

        return $name;
    }

    /**
     * 获取商品属性值id
    */
    public static function getAttrId($goods_id){

        $attr_arr = GoodsAttr::where(['goods_id' => $goods_id])->field('arrt_id')->select()->toArray();
        $attr_arr = array_column($attr_arr, 'arrt_id');
        $attr_arr = implode(',', $attr_arr);
        $attr_arr = implode(",", array_unique(explode(',', $attr_arr)));
        $attr_arr = explode(",", $attr_arr);
        $data=[];
        foreach ($attr_arr as $key=>$vs){
            $data[$vs]=$vs;
        }

        return $data;
    }
    
}